/**
 * API适配器
 */
import { QwenAPIClient } from '../qwen';
import { MultimodalInput, ChatMessage, StreamResponseListeners } from '../interfaces/qwen';

/**
 * API适配器接口
 */
export interface APIAdapter {
    /**
     * 处理多模态请求
     * @param input 多模态输入
     * @param chatHistory 聊天历史
     * @param listeners 响应监听器
     */
    handleMultimodalRequest(
        input: MultimodalInput,
        chatHistory?: ChatMessage[],
        listeners?: StreamResponseListeners
    ): Promise<void>;

    /**
     * 取消当前请求
     */
    cancelRequest(): void;
}

/**
 * 通义千问API适配器
 */
export class QwenAPIAdapter implements APIAdapter {
    private apiClient: QwenAPIClient;
    private currentController: AbortController | null = null;

    /**
     * 创建通义千问API适配器
     * @param apiKey API密钥
     */
    constructor(apiKey: string) {
        this.apiClient = new QwenAPIClient(apiKey);
    }

    /**
     * 处理多模态请求
     * @param input 多模态输入
     * @param chatHistory 聊天历史
     * @param listeners 响应监听器
     */
    async handleMultimodalRequest(
        input: MultimodalInput,
        chatHistory: ChatMessage[] = [],
        listeners: StreamResponseListeners = {}
    ): Promise<void> {
        try {
            // 取消之前的请求
            this.cancelRequest();

            // 创建新的AbortController
            this.currentController = new AbortController();

            // 发起API请求
            const response = await this.apiClient.multimodalCompletion(
                input,
                chatHistory,
                { signal: this.currentController.signal }
            );

            // 注册事件监听器
            if (listeners.onText) {
                response.onText(listeners.onText);
            }

            if (listeners.onImage) {
                response.onImage(listeners.onImage);
            }

            if (listeners.onEnd) {
                response.onEnd(listeners.onEnd);
            }

            if (listeners.onError) {
                response.onError(listeners.onError);
            }
        } catch (error) {
            // 处理请求错误
            if (listeners.onError) {
                listeners.onError(error as Error);
            } else {
                console.error('API请求失败:', error);
            }
        }
    }

    /**
     * 取消当前请求
     */
    cancelRequest(): void {
        if (this.currentController) {
            this.currentController.abort();
            this.currentController = null;
        }
    }
}

/**
 * API适配器工厂
 */
export class APIAdapterFactory {
    /**
     * 创建API适配器
     * @param type 适配器类型
     * @param apiKey API密钥
     * @returns API适配器实例
     */
    static createAdapter(type: 'qwen', apiKey: string): APIAdapter {
        switch (type) {
            case 'qwen':
                return new QwenAPIAdapter(apiKey);
            default:
                throw new Error(`不支持的适配器类型: ${type}`);
        }
    }
} 